package com.hengxinguotong.zhihuichengjian.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.MessageListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Build;
import com.hengxinguotong.zhihuichengjian.bean.BuildRes;
import com.hengxinguotong.zhihuichengjian.bean.Message;
import com.hengxinguotong.zhihuichengjian.bean.MessageListRes;
import com.hengxinguotong.zhihuichengjian.bean.MessageRes;
import com.hengxinguotong.zhihuichengjian.bean.Quality;
import com.hengxinguotong.zhihuichengjian.bean.QualityRes;
import com.hengxinguotong.zhihuichengjian.bean.Security;
import com.hengxinguotong.zhihuichengjian.bean.SecurityRes;
import com.hengxinguotong.zhihuichengjian.bean.TaskRes;
import com.hengxinguotong.zhihuichengjian.ui.building.ReplyActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.reservation.ReservationListActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.SubmitTaskActivity;
import com.hengxinguotong.zhihuichengjian.ui.quality.RectificationActivity;
import com.hengxinguotong.zhihuichengjian.ui.security.SecurityRectificationActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/7/4.
 */

public class MessageActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.tv_title_name)
    HXTextView tv_title;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.et_message_search)
    HXEditTextView et_message_search;
    @BindView(R.id.message_lv)
    PullToRefreshListView messageLv;

    private MessageActivity messageActivity;
    private MessageListAdapter adapter;
    private List<Message> messageList;
    private int pageIndex = 1;
    private String uuid, constructionid;

    @Nullable
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        ButterKnife.bind(this);
        messageActivity = this;
        messageLv.setMode(PullToRefreshListView.Mode.BOTH);
        setListener();
        uuid = SPUtil.getString(this, "uuid");
        constructionid = SPUtil.getString(this, "constructionid");
        getMessages("获取消息");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                messageLv.setRefreshing();
            }
        }, 500);
    }

//    @Override
//    protected void onStart() {
//        super.onStart();
//        messageLv.setRefreshing();
//    }

    private void setListener(){
        messageLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Message message = messageList.get(position-1);
                Intent intent = new Intent();
                String url = null;
                switch (message.getType()){
                    case 0://系统消息
                        intent.setClass(messageActivity, ReadMessageActivity.class);
                        intent.putExtra("message", message);
                        startActivityForResult(intent, message.getType());
                        break;
                    case 1://质量整改
                    case 2://安全整改
                        getSecurityById(message);
                        break;
                    case 3://任务派发
                        getTaskById(message);
                        break;
                    case 4://预约塔吊
                        intent.setClass(messageActivity, ReservationListActivity.class);
                        intent.putExtra("equipmentType", 1);
                        startActivityForResult(intent, message.getType());
                        break;
                    case 5://预约升降机
                        intent.setClass(messageActivity, ReservationListActivity.class);
                        intent.putExtra("equipmentType", 2);
                        startActivityForResult(intent, message.getType());
                        break;
                    case 6://工程进度
                        intent.setClass(messageActivity, WebViewActivity.class);
                        url = "/projectSchedule/toProgress/" + uuid + "?constructionId=" + constructionid;
                        intent.putExtra("url", url);
                        intent.putExtra("title", "工程进度");
                        startActivityForResult(intent, message.getType());
                        break;
                    case 7://PM10预警
                    case 8://噪音预警
                    case 11://PM2.5预警
                        intent.setClass(messageActivity, WebViewActivity.class);
                        url = "/environment/toReport/" + uuid + "?constructionId=" + constructionid;
                        intent.putExtra("url", url);
                        intent.putExtra("title", "环境监测");
                        startActivityForResult(intent, message.getType());
                        break;
                    case 9://塔吊预警
                        intent.setClass(messageActivity, WebViewActivity.class);
                        url = "/equipmentRegister/toTcDetail/" + uuid + "?constructionId=" + constructionid + "&equipmentId=" + message.getBillId();
                        intent.putExtra("url", url);
                        intent.putExtra("title", "塔吊预警");
                        startActivityForResult(intent, message.getType());
                        break;
                    case 10://升降机预警
                        intent.setClass(messageActivity, WebViewActivity.class);
                        url = "/equipmentRegister/toLiftDetail/" + uuid + "?constructionId=" + constructionid + "&equipmentId=" + message.getBillId();
                        intent.putExtra("url", url);
                        intent.putExtra("title", "升降机");
                        startActivityForResult(intent, message.getType());
                        break;
                    case 12://现场检查
                        getBuildById(message);//类型.1:质量检查;2:安全检查;3:日常安全检查（目前为传1）
                        break;
                    case 13://通知
                        getDetail(message);
                        break;
                }
                setMessageRead(message.getId());

            }
        });

        messageLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getMessages("获取信息");
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getMessages("获取信息");
            }
        });
    }

    private void getMessages(String alert){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("flag", "2");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, messageActivity, "/message/query/" + SPUtil.getString(messageActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(messageLv.isRefreshing()){
                    messageLv.onRefreshComplete();
                }
                if(!Utils.isEmpty(json)){
                    Gson gson = new Gson();
                    MessageListRes messageListRes = gson.fromJson(json, MessageListRes.class);
                    if(messageListRes.getStatus() == 1){
                        processMessage(messageListRes.getValue());
                    }else{
                        showEmptyView(messageLv);
                        Toast.makeText(messageActivity, "获取消息失败，请稍后重试！", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    showEmptyView(messageLv);
                }
            }

            @Override
            public void onFailure(String json) {
                if(messageLv.isRefreshing()){
                    messageLv.onRefreshComplete();
                }
                showEmptyView(messageLv);
                Toast.makeText(messageActivity, "获取消息失败，请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void processMessage(List<Message> datas){
        if(pageIndex == 1){
            if(datas.size() == 0){
                showEmptyView(messageLv);
            }else{
                dismissEmptyView();
            }
            messageList = datas;
            adapter = new MessageListAdapter(messageList, messageActivity);
            messageLv.setAdapter(adapter);
            if(datas.size() == Utils.ONCECOUNT){
                messageLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }else{
            messageList.addAll(datas);
            adapter.notifyDataSetChanged();
        }

        if(datas.size() < Utils.ONCECOUNT){
            messageLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    private void setMessageRead(String id){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, messageActivity, "/message/updateIsRead/" + SPUtil.getString(messageActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(Utils.isEmpty(json)){
                    return;
                }
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    String msg = object.getString("msg");
                    if(status == 0){
                        Toast.makeText(messageActivity, msg, Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(messageActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void pushMsg(int type, String createBy, Message message){
        RequestParams params = new RequestParams();
        params.addBodyParameter("userName", SPUtil.getString(this, "realName"));
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
        params.addBodyParameter("type", type + "");//类型.1:质量检查;2:安全检查;3:日常安全检查（目前为传1）
        params.addBodyParameter("createBy", createBy);
        params.addBodyParameter("msgId", message.getId());
        params.addBodyParameter("status", 1 + "");//从消息列表跳转消息状态 1未读 0已读（从消息列表跳转时传否则不传）

        Utils.requestData(null, messageActivity, "/inspection/pushMsg/" + SPUtil.getString(messageActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(Utils.isEmpty(json)){
                    return;
                }
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    String msg = object.getString("msg");
                    if(status == 0){
                        Toast.makeText(messageActivity, msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(messageActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getTaskById(final Message message){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("taskId", message.getBillId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Utils.requestData("加载中…", this, "/taskDistribution/queryByTaskId/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    TaskRes taskRes = gson.fromJson(json, TaskRes.class);
                    if(taskRes.getStatus() == 1){
                        Intent intent = new Intent();
                        intent.setClass(messageActivity, SubmitTaskActivity.class);
                        intent.putExtra("task", taskRes.getValue());
                        startActivityForResult(intent, message.getType());
                    }else{
                        showToast(taskRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(messageActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getDetail(final Message message){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", message.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Utils.requestData("加载中…", this, "/notice/getDetail/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    MessageRes messageRes = gson.fromJson(json, MessageRes.class);
                    if(messageRes.getStatus() == 1){
                        Message notice = messageRes.getValue();
                        if(notice != null ) {
                            Intent intent = new Intent();
                            intent.setClass(messageActivity, ReadMessageActivity.class);
                            intent.putExtra("message", notice);
                            startActivityForResult(intent, message.getType());
                        }else{
                            showToast("通知信息为空");
                        }
                    }else{
                        showToast(messageRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(messageActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getBuildById(final Message message){
        Utils.requestData("加载中…", this, "/build/queryByInspectionId/" + SPUtil.getString(this, "uuid") + "?id=" + message.getBillId(), null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    BuildRes siteRes = gson.fromJson(json, BuildRes.class);
                    if(siteRes.getStatus() == 1){
                        Build build = siteRes.getValue();
                        if(build != null ) {
                            if(message.getIsRead() == 0){
//                                pushMsg(Constants.QUALITY, build.getCreateBy(), message);
                            }
                            Intent intent = new Intent();
                            intent.setClass(messageActivity, ReplyActivity.class);
                            intent.putExtra("type", Constants.LIVE);
                            intent.putExtra("state", build.getCorrectiveStatus());
                            intent.putExtra("build", build);
                            startActivityForResult(intent, message.getType());
                        }else{
                            showToast("检查单数据为空");
                        }
                    }else{
                        showToast(siteRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(messageActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getSecurityById(final Message message){
        Utils.requestData("加载中…", this, "/inspection/queryByInspectionId/" + SPUtil.getString(this, "uuid") + "?id=" + message.getBillId(), null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    switch (message.getType()){
                        case 1:
                            QualityRes qualityRes = gson.fromJson(json, QualityRes.class);
                            if(qualityRes.getStatus() == 1){
                                Quality quality = qualityRes.getValue();
                                if(quality != null ) {
                                    Intent intent = new Intent();
                                    intent.setClass(messageActivity, RectificationActivity.class);
                                    intent.putExtra("type", message.getType());
                                    intent.putExtra("quality", quality);
                                    startActivityForResult(intent, message.getType());
                                }else{
                                    showToast("检查单数据为空");
                                }
                            }else{
                                showToast(qualityRes.getMsg());
                            }
                            break;
                        case 2:
                            SecurityRes securityRes = gson.fromJson(json, SecurityRes.class);
                            if(securityRes.getStatus() == 1){
                                Security security = securityRes.getValue();
                                if(security != null ) {
                                    Intent intent = new Intent();
                                    intent.setClass(messageActivity, SecurityRectificationActivity.class);
                                    intent.putExtra("type", message.getType());
                                    intent.putExtra("security", security);
                                    startActivityForResult(intent, message.getType());
                                }else{
                                    showToast("检查单数据为空");
                                }
                            }else{
                                showToast(securityRes.getMsg());
                            }
                            break;
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(messageActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick({R.id.iv_back})
    public void onClick(View v) {
        finish();
    }
}
